package com.sayyi.validate.constraints.custom;

import com.sayyi.validate.valid.ValidateMapCache;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Map;

/**
 * @author xuchuang
 * date 2021/12/2 5:36 下午
 */
public class ExistValidator implements ConstraintValidator<Exist, Object> {

    private String setKey;

    @Override
    public void initialize(Exist constraintAnnotation) {
        setKey = constraintAnnotation.value();
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        if (value == null) {
            return true;
        }
        Map<Object, Object> sets = ValidateMapCache.get(setKey);
        if (setKey == null) {
            return true;
        }
        return sets.containsKey(value);
    }

}
